package net.hhk.twitter;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.hhk.connect.HTTPConnect;
import net.hhk.controller.TweetAdapter;
import net.hhk.controller.TweetManager;
import net.hhk.controller.UserAdapter;
import net.hhk.controller.lazyload.ImageLoader;
import net.hhk.data.Constant;
import net.hhk.data.MySharePreferences;
import net.hhk.data.Tweet;
import net.hhk.data.User;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.TextPaint;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.text.util.Linkify.TransformFilter;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class UserProfileActivity extends Activity implements OnClickListener {
	public User user;
	public int userid;
	private TweetManager mgr;
	private String username = "";
	private MySharePreferences sharePre;
	private ImageLoader imageLoader;
	private static LayoutInflater inflater = null;
	private Context context;
	private Boolean isMyProfile = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle b = getIntent().getExtras();
		userid = b.getInt("id");
		user = new User();
		mgr = new TweetManager(getApplicationContext());

		inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		imageLoader = new ImageLoader(this);

		sharePre = (MySharePreferences) getApplicationContext();
		int myid = sharePre.getExitInt("myid", 0);
		if (userid < 1) {
			Uri data = getIntent().getData();
			if (data != null) {
				String url = data.toString();
				username = url.substring(url.indexOf("@") + 1);

			} else {
				username = sharePre.getExitString("currentVisitUsername");
			}
			String myUserName = sharePre.getExitString("myUsername");
			if (myUserName.equals(username))
				isMyProfile = true;
		} else if (userid == myid) {
			isMyProfile = true;
		}
		if (!isMyProfile)
			setContentView(R.layout.user_layout);
		else
			setContentView(R.layout.my_profile_layout);
		getUserInfo(userid);
		getTotalTweet(user.getUserid());
		showProfile();
		
		LinearLayout write_tweet = (LinearLayout) findViewById(R.id.home_write_tweet);
		write_tweet.setOnClickListener(clickWriteTweet);
		
		Button btn = (Button) findViewById(R.id.btn_tweet);
		btn.setOnClickListener(clickWriteTweet);
		
		LinearLayout searchLayout = (LinearLayout) findViewById(R.id.btnSearch_layout);
		searchLayout.setOnClickListener(clickSearch);
		Button btnSearch = (Button) findViewById(R.id.btn_search);
		btnSearch.setOnClickListener(clickSearch);
		
		RelativeLayout tweets_layout = (RelativeLayout) findViewById(R.id.user_profile_tweets_layout);
		tweets_layout.setOnClickListener(this);
		RelativeLayout following_layout = (RelativeLayout) findViewById(R.id.user_profile_following_layout);
		following_layout.setOnClickListener(this);
		RelativeLayout follower_layout = (RelativeLayout) findViewById(R.id.user_profile_follower_layout);
		follower_layout.setOnClickListener(this);

		RelativeLayout user_following = (RelativeLayout) findViewById(R.id.user_layout_following);
		user_following.setOnClickListener(this);
		RelativeLayout user_follower = (RelativeLayout) findViewById(R.id.user_layout_follower);
		user_follower.setOnClickListener(this);
		RelativeLayout user_favorite = (RelativeLayout) findViewById(R.id.user_layout_favorite);
		user_favorite.setOnClickListener(this);
		RelativeLayout user_all_tweet = (RelativeLayout) findViewById(R.id.user_profil_view_all_tweet_btn);
		user_all_tweet.setOnClickListener(this);
		if (!isMyProfile) {
			Button follow_button = (Button) findViewById(R.id.user_profile_follow_button);
			follow_button.setOnClickListener(this);
		} else {
			Button editButton = (Button) findViewById(R.id.edit_profile);
			editButton.setOnClickListener(this);
		}
		if (user.getTweer_number() > 0)
			loadData();

	}
	private OnClickListener clickSearch = new OnClickListener() {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent i = new Intent(getApplicationContext(), SearchActivity.class);

			startActivity(i);

		}
	};

	private OnClickListener clickWriteTweet = new OnClickListener() {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent i = new Intent(getApplicationContext(),
					WriteTweetActivity.class);
			Bundle b = new Bundle();

			b.putInt("isReply", 0);
			i.putExtras(b);
			startActivity(i);

		}
	};

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (user.getTweer_number() > 0)
			loadData();
		reLoadData();
	}

	public void getUserInfo(int id) {
		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		String result = "";
		if (username.length() > 0) {
			postParameters.add(new BasicNameValuePair("username", username));
			HTTPConnect http = HTTPConnect.getConnect();
			result = http.doConnect(Constant.USER_INFO_BY_USERNAME,
					postParameters);
		} else {
			postParameters.add(new BasicNameValuePair("userid", Integer
					.toString(id)));
			HTTPConnect http = HTTPConnect.getConnect();
			result = http.doConnect(Constant.USER_INFO_BY_USERID,
					postParameters);
		}
		// result =result.trim();
		try {
			JSONObject obj = new JSONObject(result);
			user.setUserid(obj.getInt("id"));
			user.setEmail(obj.getString("email"));
			user.setUsername(obj.getString("username"));
			user.setFullname(obj.getString("screenName"));
			user.setAvatar(obj.getString("avatar"));
			user.setIsfollowed(obj.getBoolean("isFollow"));
			user.setBio(obj.getString("Bio"));
			user.setWeb(obj.getString("website"));
			user.setLocation(obj.getString("country"));
		} catch (Exception e) {
			e.printStackTrace();
			sharePre.setExitString(Constant.ERROR_NOT_FOUND_USER, "true");
			sharePre.setExitString("MeassageError", "Not found user");
			finish();

		}
	}

	public void getTotalTweet(int id) {
		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("userid", Integer
				.toString(id)));
		HTTPConnect http = HTTPConnect.getConnect();
		String result = http.doConnect(Constant.USER_TOTAL_TWEET_BY_USERID,
				postParameters);
		try {

			JSONObject obj = new JSONObject(result);
			user.setTweer_number(obj.getInt("totalTweet"));
			user.setFollower(obj.getInt("totalFollower"));
			user.setFollowing(obj.getInt("totalFollowing"));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void showProfile() {
		ImageView profile_pictue = (ImageView) findViewById(R.id.user_profile_picture);
		imageLoader.DisplayImage(user.getAvatar(), profile_pictue);
		TextView fullname = (TextView) findViewById(R.id.user_profile_fullname);
		fullname.setText(user.getFullname());
		TextView tweet = (TextView) findViewById(R.id.user_profile_tweets);
		tweet.setText(Integer.toString(user.getTweer_number()));
		TextView follower = (TextView) findViewById(R.id.user_profile_follower_1);
		follower.setText(Integer.toString(user.getFollower()));

		if (user.getBio() != null) {
			if (user.getBio().length() > 0) {
				TextView bio = (TextView) findViewById(R.id.user_profile_bio);
				bio.setVisibility(View.VISIBLE);
				bio.setText(user.getBio());
			}
		}
		if (user.getWeb() != null) {
			if (user.getWeb().length() > 0) {
				TextView web = (TextView) findViewById(R.id.user_profile_web);
				web.setVisibility(View.VISIBLE);
				web.setText(user.getWeb());
				TransformFilter transformFilter = new TransformFilter() {
					public final String transformUrl(final Matcher match,
							String url) {
						return "com.example.test";
					}
				};
				Pattern urlPattern = Patterns.WEB_URL;
				Linkify.addLinks(web, urlPattern, null, null, transformFilter);
				stripUnderlines(web);
			}
		}

		TextView following = (TextView) findViewById(R.id.user_profile_following);
		following.setText(Integer.toString(user.getFollowing()));
		if (!isMyProfile) {
			Button follow_button = (Button) findViewById(R.id.user_profile_follow_button);
			follow_button.setOnClickListener(this);
			if (!user.isIsfollowed())
				follow_button.setText("Follow");
			else
				follow_button.setText("Following");
		}
		TextView title = (TextView) findViewById(R.id.user_profile_title);
		title.setText("@" + user.getUsername());
		title.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(getApplicationContext(),
						MainActivity.class);
				i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(i);
				finish();
			}
		});

	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.user_profile_tweets_layout:
			viewAllTweet();

			break;
		case R.id.user_profile_following_layout:
			viewAllFollowing();
			break;

		case R.id.user_profile_follower_layout:
			viewAllFollower();
			break;
		case R.id.user_profile_follow_button:
			Button follow_button = (Button) findViewById(R.id.user_profile_follow_button);

			if (user.isLastStatus()) {
				user.setLastStatus(false);
				follow_button.setText("follow");
			} else {
				user.setLastStatus(true);
				follow_button.setText("following");
			}
			break;
		case R.id.user_layout_following:
			viewAllFollowing();
			// finish();

			break;
		case R.id.user_layout_follower:
			viewAllFollower();
			// finish();
			break;
		case R.id.user_layout_favorite:
			Intent user_favorite = new Intent(getApplicationContext(),
					MyFavoriteActivity.class);
			Bundle use_favorite = new Bundle();

			use_favorite.putInt("id", user.getUserid());
			user_favorite.putExtras(use_favorite);
			startActivity(user_favorite);
			// finish();
			break;
		case R.id.user_profil_view_all_tweet_btn:
			viewAllTweet(); // finish();
			break;
		case R.id.edit_profile:
			Intent i = new Intent(getApplicationContext(),
					EditProfileActivity.class);
			Bundle b = new Bundle();
			b.putInt("id", user.getUserid());
			b.putString("name", user.getFullname());
			b.putString("bio", user.getBio());
			b.putString("website", user.getWeb());
			b.putString("location", user.getLocation());
			b.putString("avatar", user.getAvatar());
			i.putExtras(b); // Put your id to your next Inten
			startActivity(i);
			break;
		default:
			break;
		}
	}

	public void viewAllTweet() {
		Intent user_all_tweet = new Intent(getApplicationContext(),
				MyTweetActivity.class);
		Bundle use_all_tweet = new Bundle();

		use_all_tweet.putInt("id", user.getUserid());
		user_all_tweet.putExtras(use_all_tweet);
		startActivity(user_all_tweet);
	}

	public void viewAllFollower() {
		Intent user_follower = new Intent(getApplicationContext(),
				UserFollowActivity.class);
		Bundle use_follower = new Bundle();
		use_follower.putBoolean("isfollowing", false);
		use_follower.putInt("id", user.getUserid());
		user_follower.putExtras(use_follower);
		startActivity(user_follower);
	}

	public void viewAllFollowing() {
		Intent user_following = new Intent(getApplicationContext(),
				UserFollowActivity.class);
		Bundle user_followe = new Bundle();
		user_followe.putBoolean("isfollowing", true);
		user_followe.putInt("id", user.getUserid());
		user_following.putExtras(user_followe);
		startActivity(user_following);
	}

	private void loadData() {
		AsyncTask<String, Void, List<Tweet>> asyncTask = new AsyncTask<String, Void, List<Tweet>>() {
			// private ProgressDialog progressDialog = new ProgressDialog(
			// UserProfileActivity.this);

			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPreExecute()
			 */
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// progressDialog.setTitle("Loading Users");
				// if (!progressDialog.isShowing()) {
				// progressDialog.show();
				// }
			}

			@Override
			protected List<Tweet> doInBackground(String... params) {
				// Following actions will be done in background

				return mgr.getSocialFeed(Constant.GET_USER_TWEET,
						user.getUserid(), 1, 3);
			}

			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
			 */
			@Override
			protected void onPostExecute(List<Tweet> result) {
				super.onPostExecute(result);
				if (result.size() > 0) {
					loadThreeTweetCurrent(result);
				}

			}
		};
		asyncTask.execute("Saurabh");
	}

	private void reLoadData() {
		AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPreExecute()
			 */
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
			}

			@Override
			protected String doInBackground(String... params) {
				// Following actions will be done in background
				getUserInfo(userid);
				getTotalTweet(user.getUserid());
				return "";

			}

			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
			 */
			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				showProfile();
			}
		};
		asyncTask.execute("Saurabh");
	}

	public void loadThreeTweetCurrent(List<Tweet> reply_manager) {
		if (reply_manager.size() > 0) {
			LinearLayout list = (LinearLayout) findViewById(R.id.list);
			list.setVisibility(View.VISIBLE);
			list.removeAllViewsInLayout();
			LinearLayout tweets_title = (LinearLayout) findViewById(R.id.tweets_title);
			tweets_title.setVisibility(View.VISIBLE);

			for (int i = 0; i < reply_manager.size(); i++) {

				final Tweet twit = reply_manager.get(i);

				// LinearLayout list = (LinearLayout)
				// findViewById(R.id.reply_from_lis);

				list.addView(loadView(twit));

			}

		}

	}

	public View loadView(Tweet twett) {
		final Tweet twit = twett;
		View row = inflater.inflate(R.layout.tweet_layout, null);
		final TextView profileName = (TextView) row
				.findViewById(R.id.profileName);
		profileName.setText(twit.getFullName());
		final TextView username = (TextView) row.findViewById(R.id.userName);
		username.setText(" @" + twit.getUserName());
		ImageView image = (ImageView) row.findViewById(R.id.profileImage);

		imageLoader.DisplayImage(twit.getImageUrl(), image);

		final TextView twitMessage = (TextView) row
				.findViewById(R.id.twitMessage);
		twitMessage.setText(twit.getTweetText());
		int isRetweet = twit.getIsRetweet();
		if (isRetweet > 0) {
			final ImageView retweet_image = (ImageView) row
					.findViewById(R.id.image_retweet);
			retweet_image.setVisibility(View.VISIBLE);
			final TextView retweet_user = (TextView) row
					.findViewById(R.id.name_user_retweet);
			retweet_user.setText("  Retweeted by " + twit.getNameRweet());
		}

		final ImageView favorRetweet = (ImageView) row
				.findViewById(R.id.favor_retweet);
		if (twit.getIsMyFavorite() && twit.getIsMyRetweet()) {
			favorRetweet.setVisibility(View.VISIBLE);
			favorRetweet.setBackgroundResource(R.drawable.ic_dogear_both);
		} else if (twit.getIsMyFavorite()) {
			favorRetweet.setVisibility(View.VISIBLE);
			favorRetweet.setBackgroundResource(R.drawable.ic_dogear_fave);
		} else if (twit.getIsMyRetweet()) {
			favorRetweet.setVisibility(View.VISIBLE);
			favorRetweet.setBackgroundResource(R.drawable.ic_dogear_rt);
		} else
			favorRetweet.setVisibility(View.GONE);
		row.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(getApplicationContext(),
						ViewTweetActivity.class);
				Bundle b = new Bundle();
				b.putInt("id", twit.getTweetId());
				b.putString("retweetUser", twit.getNameRweet());
				b.putBoolean("isfavorite", twit.getIsMyFavorite());
				b.putBoolean("isretweet", twit.getIsMyRetweet());
				sharePre.setExitString("currentVisitUsername",
						twit.getUserName());
				i.putExtras(b); // Put your id to your next Inten
				sharePre.setExitString("currentVisitUsername",
						twit.getUserName());
				startActivity(i);

			}
		});
		return row;
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		HTTPConnect http = HTTPConnect.getConnect();
		postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("userid_array", Integer
				.toString(user.getUserid())));
		if (user.isIsfollowed()) {
			if (!user.isLastStatus()) {
				String result2 = http.doConnect(Constant.SET_UN_FOLLOW,
						postParameters);
			}

		} else {
			if (user.isLastStatus()) {
				String result = http.doConnect(Constant.SET_FOLLOW,
						postParameters);
			}
		}

	}

	private void stripUnderlines(TextView textView) {
		Spannable s = null;
		try {
			s = (Spannable) textView.getText();

		} catch (Exception e) {
			// TODO: handle exception
			return;
		}

		URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
		for (URLSpan span : spans) {
			int start = s.getSpanStart(span);
			int end = s.getSpanEnd(span);
			s.removeSpan(span);
			span = new URLSpanNoUnderline(span.getURL());
			s.setSpan(span, start, end, 0);
		}
		textView.setText(s);
	}

	private class URLSpanNoUnderline extends URLSpan {
		public URLSpanNoUnderline(String url) {
			super(url);
		}

		@Override
		public void updateDrawState(TextPaint ds) {
			super.updateDrawState(ds);
			ds.setUnderlineText(false);
		}
	}
}
